package com.zzyl.service.impl;

import cn.hutool.crypto.digest.BCrypt;
import cn.hutool.json.JSONUtil;
import com.zzyl.dto.LoginDto;
import com.zzyl.mapper.UserMapper;
import com.zzyl.properties.JwtTokenManagerProperties;
import com.zzyl.properties.PublicAccessUrlsConfigProperties;
import com.zzyl.service.LoginService;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.ObjectUtil;
import com.zzyl.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private JwtTokenManagerProperties jwtTokenManagerProperties;
    @Autowired
    private PublicAccessUrlsConfigProperties publicAccessUrlsConfigProperties;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Override
    public UserVo login(LoginDto loginDto) {
        //判断用户名是否存在
        UserVo userVo =userMapper.selectByUsername(loginDto.getUsername());
        if(ObjectUtil.isEmpty(userVo)){
            throw new RuntimeException("用户名不存在");
        }
        //用户是否被禁用
        if(userVo.getDataState().equals("1")){
            throw new RuntimeException("用户已被禁用");
        }
        //密码是否正确
        if(!BCrypt.checkpw(loginDto.getPassword(),userVo.getPassword())){
            throw new RuntimeException("密码错误");
        }
        //授权
        //查询当前用户权限
        List<String> resourcesUrl =userMapper.queryResourcesUrl(userVo.getId());
        List<String> publicAccessUrls = publicAccessUrlsConfigProperties.getPublicAccessUrls();
        resourcesUrl.addAll(publicAccessUrls);
        //将菜单存储到redis中 键为id "user:public_access_urls:"是分层用的
        redisTemplate.opsForValue().set("user:public_access_urls:"+userVo.getId(),JSONUtil.toJsonStr(resourcesUrl),jwtTokenManagerProperties.getTtl()/1000, TimeUnit.SECONDS);
        //隐藏当前密码
        userVo.setPassword("");
        //构建令牌
        HashMap<String, Object> claims = new HashMap<>();
        claims.put("currentUser", JSONUtil.toJsonStr(userVo));
        String token = JwtUtil.createJWT(jwtTokenManagerProperties.getBase64EncodedSecretKey(), jwtTokenManagerProperties.getTtl(), claims);
        userVo.setUserToken(token);
        return userVo;
    }
}
